package com.demo; /**
 * @author wzm
 * @create 2023-09-20 11:12
 * project_name:javaweb2308
 */

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //处理登录的逻辑
        //1.设置编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;chatset=UTF-8");

        //2.获取请求过来的用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");

//        User login = new User(null, username, password);

        //3.和数据库查询出来的数据进行对比
            //查询数据库里的信息
        Connection conn = JDBCUtils.getConn();
        String sql = "select * from user where username = ? and password = ?";
        QueryRunner queryRunner = new QueryRunner();
        User user = null;
        try {
            user = queryRunner.query(conn, sql, new BeanHandler<>(User.class),username,password);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        //用用户输入的信息和数据对比

        //4.根据对比结果 响应具体的内容
        if(user != null){
            //数据库确实存在用户名和密码匹配的数据 成功跳转首页
            //response.getWriter().write("登录成功");
            request.getRequestDispatcher("/index.jsp").forward(request,response);
        }else{
            //登陆失败 留在登录页面
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }





    }
}
